package com.amor.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hy.frame.mvvm.net.BaseResponse
import com.hy.frame.mvvm.state.ResultState
import com.hy.frame.mvvm.state.handle
import com.hy.frame.mvvm.state.handleException
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * title BaseViewModel
 * author HeYan
 * date 2021/9/25
 * desc
 */
abstract class BaseViewModel : com.hy.frame.mvvm.base.BaseViewModel() {

    /**
     * net request 自动校验请求结果数据是否是成功
     * @param block 请求体方法
     * @param result 请求回调的ResultState数据
     * @param loadingEnabled 是否显示加载框
     * @param loadingMsg 加载框提示内容
     */
    protected fun <T> requestExt(
        block: suspend () -> BaseResponse<T>,
        result: MutableLiveData<ResultState<T>>,
        loadingEnabled: Boolean = false,
        loadingMsg: String? = "加载中...",
        flag: String? = null
    ): Job {
        return viewModelScope.launch {
            runCatching {
                //加载中
                result.value = ResultState.newLoading(loadingMsg)
                if (loadingEnabled)
                    loadingUI.value = Loading(true, loadingMsg)
                //请求体
                block()
            }.onSuccess {
                if (loadingEnabled)
                    loadingUI.value = Loading(false)
                result.handle(it, flag)
            }.onFailure {
                it.printStackTrace()
                if (loadingEnabled)
                    loadingUI.value = Loading(false)
                result.handleException(it, flag)
            }
        }

    }
}